#include"Req.h"
#include<sstream>
#include<iostream>
#include<regex>
#include<memory>
#include"ValuesData.h"
#include"FormData.h"
#include"JsonData.h"

void Req::dealData(){
  if(head->sf == "POST"){
    std::string &ct = head->h["content-type:"];
    if(std::regex_search(ct, std::regex("form-data"))){
      auto &&f = std::make_shared<FormData>();
      f->type = "form";
      f->setFormData(ct, body.str());
      data = f;
    }else if(std::regex_search(ct, std::regex("www-form"))){
      auto &&v = std::make_shared<ValuesData>();
      v->type = "values";
      v->setValues(body.str());
      data = v;
    }else{
      auto &&j = std::make_shared<JsonData>();
      j->type = "json";
      j->setJson(body.str());
      data = j;
    }
  }else{
    std::smatch m;
    if(std::regex_search(head->ss, m, std::regex("\\S*(?=\\?)"))){
      head->ss = m[0];
      std::string &&values = m.suffix();
      auto &&v = std::make_shared<ValuesData>();
      v->setValues(values.substr(1, values.length()-1));
      v->type = "values";
      data = v;
    }
  }
  body.str("");
}

void Req::startBody(){
  overHead = true;
  auto &&d = body.str();
  std::smatch m;
  std::regex_search(d, m, std::regex("[\\S\\s]+?\r\n\r\n"));
  head = std::make_shared<Header>(m[0]);
  if(head->h.find("content-length:") != head->h.end()){
    body.str("");
    body << d.substr(m[0].length(), d.length()-m[0].length());
    std::istringstream iss(head->h["content-length:"]);
    iss >> bl;
    bl -= body.tellp();
  }else{
    bl = 0;
  }
}
